package xzy.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
import xzy.dao.TeacherMapper;
import xzy.pojo.Teacher;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "TeacherLogin_Servlet")
public class teacherLogin_Servlet extends HttpServlet {
    ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
    TeacherMapper teacherMapper= (TeacherMapper) context.getBean("teacherMapper");
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
        System.out.println("教师端登录");
        String teacherName=request.getParameter("userName");
        String teacherPwd=request.getParameter("password");
        request.setAttribute("userName",teacherName);
        request.setAttribute("password",teacherPwd);
        HttpSession session=request.getSession();
        try{
            if(!StringUtils.isEmpty(teacherName)&&!StringUtils.isEmpty(teacherPwd)) {
                Teacher teacher =teacherMapper.findTeacherByName(teacherName);
                if(teacher!=null && teacher.getTeacherPwd().equals(teacherPwd)){
//                客户端跳转
                    session.setAttribute("user",teacherName);
                    if(!teacherName.equals("admin")){
                        session.setAttribute("teacherName",teacherName);
                    }
                    request.setAttribute("error","");
                    request.getRequestDispatcher("/Student-info.jsp").forward(request,response);
                }else {
                    request.setAttribute("error","用户名不存在或者密码错误");
                    request.getRequestDispatcher("/index2.jsp").forward(request,response);
                }
            }else {

                request.setAttribute("error","用户名或者密码为空");
                request.getRequestDispatcher("/index2.jsp").forward(request,response);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            request.setAttribute("error","用户名不存在或者密码错误");
            request.getRequestDispatcher("/index2.jsp").forward(request,response);
        }finally {
        }
    }
}
